package com.cssw.fyzb.web.service;

import com.cssw.fyzb.base.web.domain.AjaxData;
import com.cssw.fyzb.core.dao.system.MenuDao;
import com.cssw.fyzb.core.model.dodb.SysFunc;
import com.cssw.fyzb.web.util.TreeUtil;
import com.cssw.fyzb.web.vo.FuncTreeNodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Author yangyiqun
 * @create 2020-08-10 11:15
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;


    @Override
    public AjaxData getMenuTree(Long operId) {

        List<SysFunc> funcList = null;

            funcList = menuDao.queryFuncListByOperId(operId);
        List<FuncTreeNodeVo> h_funcTrees = new ArrayList<>();

        if (null == funcList || funcList.isEmpty()){
            return AjaxData.success();
        }

        FuncTreeNodeVo h_funcTree = null;
        for (SysFunc func : funcList) {
            h_funcTree = new FuncTreeNodeVo();
            h_funcTree.setFuncCode(func.getFuncCode());
            h_funcTree.setFuncIcon(func.getFuncIcon());
            h_funcTree.setName(func.getFuncName());
            h_funcTree.setId(func.getFuncId().toString());
            if (null != func.getSupFuncId()) {
                h_funcTree.setpId(func.getSupFuncId().toString());
            }
            h_funcTree.setFuncId(func.getFuncId());
            h_funcTree.setFuncName(func.getFuncName());
            h_funcTree.setFuncType(func.getFuncType());
            h_funcTree.setFuncUrl(func.getFuncUrl());
            h_funcTree.setpFuncId(func.getFuncId());
            h_funcTree.setFuncIcon(func.getFuncIcon());
            h_funcTree.setSort(func.getSort());
            h_funcTrees.add(h_funcTree);
        }

        List<FuncTreeNodeVo> h_funcTreesBuild = TreeUtil.build(h_funcTrees, "0");

        funcTreeSort(h_funcTreesBuild);

        return AjaxData.success(h_funcTreesBuild);
    }


    private void funcTreeSort(List<FuncTreeNodeVo> funcTrees){
        if (null == funcTrees){
            return;
        }
        funcTrees.sort(Comparator.comparing(FuncTreeNodeVo::getSort, Comparator.nullsLast(Integer::compareTo)));

        if (null != funcTrees) {
            for (FuncTreeNodeVo funcTree : funcTrees) {
                List<FuncTreeNodeVo> childFuncTrees = (List)funcTree.getChildren();
                funcTreeSort(childFuncTrees);
            }
        }
    }
}
